package com.example.writting.ui.examples

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.writting.R
import com.example.writting.model.Example

class ExampleAdapter(
    private val onExampleClick: (Example) -> Unit
) : RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder>() {

    private var examples: List<Example> = emptyList()

    fun updateExamples(newExamples: List<Example>) {
        val diffCallback = object : DiffUtil.Callback() {
            override fun getOldListSize() = examples.size
            override fun getNewListSize() = newExamples.size
            override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
                examples[oldItemPosition].title == newExamples[newItemPosition].title
            override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
                examples[oldItemPosition] == newExamples[newItemPosition]
        }
        val diffResult = DiffUtil.calculateDiff(diffCallback)
        examples = newExamples
        diffResult.dispatchUpdatesTo(this)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_example, parent, false)
        return ExampleViewHolder(view)
    }

    override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
        holder.bind(examples[position], position + 1)
    }

    override fun getItemCount(): Int = examples.size

    inner class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val titleTextView: TextView = itemView.findViewById(R.id.exampleTitleTextView)

        fun bind(example: Example, number: Int) {
            titleTextView.text = "${number}. ${example.title}"
            itemView.setOnClickListener { onExampleClick(example) }
        }
    }
} 